//
//  UpdateViewController.m
//  TestARC
//
//  Created by 晓泉 吴 on 12-9-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UpdateViewController.h"
#import "MyExtensions.h"
#import "JSON/SBJson.h"

@interface UpdateViewController ()

@end

@implementation UpdateViewController
@synthesize progressView,indicatorView,hipLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title=@"更新";
    self.progressView.progress = 0.0f;
    self.indicatorView.hidden = YES;
    self.hipLabel.hidden = YES;
    self.timeLabel.text = @"请点击更新按钮进行更新";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.progressView = nil;
    self.indicatorView = nil;
    self.hipLabel = nil;
    self.timeLabel = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)update:(id)sender
{
    [self showWaitView:nil];
    
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    
    NSString *URL_UPDATE = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet?style=8b833da7cd540170b8b513d84b0f2df1&timestamp=%d",timestamp];
    //NSLog(@"update = %@",URL_UPDATE);
    NSURL *url = [NSURL URLWithString:URL_UPDATE];
    request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        
        [self hideWaitView];
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        //NSLog(@"responseString = %@",responseString);
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            NSLog(@"%@",[json objectForKey:@"message"]);
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"网络加载错误"
                                  message:[NSString stringWithFormat:@"%@,请重试.",[json objectForKey:@"message"]]
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return ;
        }
        
        NSDictionary *dbInfo = [[json objectForKey:@"dbinfo"]objectAtIndex:0];
        serverVersion = [[dbInfo objectForKey:@"version"]intValue];
        int localVersion = 1;
        NSString *dbUrl = [dbInfo objectForKey:@"dbUrl"];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *VERSION_KEY = @"local_version";
        NSString *localVersionStr = [defaults stringForKey:VERSION_KEY];
        if ([localVersionStr isEmpty]) {
            NSLog(@"第一次设置版本号");
            [defaults setObject:@"0" forKey:VERSION_KEY];
            localVersion = 1;
        }
        else
        {
            localVersion = [localVersionStr intValue];
            NSLog(@"本地版本号存在:%d",localVersion);
        }
        
        if (serverVersion > localVersion) {//todo 去掉等号
            NSLog(@"更新数据库！url=%@",dbUrl);
            [self downloadDBFile:dbUrl];
            //[self downloadDBFile:@"http://dsshjava1.gotoip3.com/weibotest/yaoxiadb.db"];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"检测完毕"
                                  message:@"当前数据库为最新版,无须更新"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            self.timeLabel.text = @"最近更新完成";
        }
        
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        [self hideWaitView];
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];

}

-(void)downloadDBFile:(NSString *)dbUrl
{
    self.indicatorView.hidden = NO;
    self.hipLabel.hidden = NO;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * toPath =   [documentsDirectory stringByAppendingPathComponent:@"yaoxiadb.db"];
    NSString * tempPath = [documentsDirectory stringByAppendingPathComponent:@"temp.db"];
    
    
    NSURL *url = [NSURL URLWithString:dbUrl];
    ASIHTTPRequest *asiRequest = [ASIHTTPRequest requestWithURL:url];
    [asiRequest setDownloadDestinationPath:tempPath];
    [asiRequest setDownloadProgressDelegate:self.progressView];
    [asiRequest startSynchronous];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    if(![fileManager fileExistsAtPath:tempPath])
    {
        NSLog(@"下载未完成！");
        return;
    }
    if ([fileManager fileExistsAtPath:toPath]) {
        [fileManager removeItemAtPath:toPath error:&error];
    }
    
    BOOL success = [fileManager copyItemAtPath:tempPath toPath:toPath error:&error];
    if (success) {
        NSLog(@"change db file:YES");
        
    } else {
        NSLog(@"change db file:NO,erro:%@",error);
        return;
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSString stringWithFormat:@"%d",serverVersion] forKey:@"local_version"];
    self.indicatorView.hidden = YES;
    self.hipLabel.hidden = YES;
    self.timeLabel.text = @"最近更新完成";
}

@end
